<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="应用名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入应用名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="应用类别" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择应用类别" clearable>
          <el-option
            v-for="dict in dict.type.app_catgory"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="应用状态" prop="status">-->
<!--        <el-select v-model="queryParams.status" placeholder="请选择应用状态" clearable>-->
<!--          <el-option-->
<!--            v-for="dict in dict.type.app_status"-->
<!--            :key="dict.value"-->
<!--            :label="dict.label"-->
<!--            :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['appstoredev:app:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['appstoredev:app:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['appstoredev:app:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['appstoredev:app:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="appList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" width="50" prop="id" />
      <el-table-column label="应用名称" align="center" prop="name" />
      <el-table-column label="应用图标" align="center" prop="iconUrl" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.iconUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="应用类别" align="center" prop="categoryId">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.app_catgory" :value="scope.row.categoryId"/>
        </template>
      </el-table-column>
      <el-table-column label="应用版本号" align="center" width="100" prop="version" />
<!--      <el-table-column label="应用状态" align="center" prop="status">-->
<!--        <template slot-scope="scope">-->
<!--          <dict-tag :options="dict.type.app_status" :value="scope.row.status"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="应用评分" align="center" width="50" prop="rating" />
      <el-table-column label="下载数量" align="center" width="50" prop="downloadCount" />

      <el-table-column label="应用大小" align="center" prop="size" />
      <el-table-column label="BUNDLE NAME" align="center" prop="bundleName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['appstoredev:app:edit']"
          >更新</el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['appstoredev:app:remove']"-->
<!--          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改应用详情对话框 -->
<!--    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>-->
<!--      <el-form ref="form" :model="form" :rules="rules" label-width="80px">-->
<!--        <el-form-item label="应用名称" prop="name">-->
<!--          <el-input v-model="form.name" placeholder="请输入应用名称" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="应用描述" prop="description">-->
<!--          <el-input v-model="form.description" placeholder="请输入应用描述" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="应用类别" prop="categoryId">-->
<!--          <el-select v-model="form.categoryId" placeholder="请选择应用类别">-->
<!--            <el-option-->
<!--              v-for="dict in dict.type.app_catgory"-->
<!--              :key="dict.value"-->
<!--              :label="dict.label"-->
<!--              :value="parseInt(dict.value)"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="发布者ID" prop="developerId">-->
<!--          <el-input v-model="form.developerId" placeholder="请输入发布者ID" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="应用版本号" prop="version">-->
<!--          <el-input v-model="form.version" placeholder="请输入应用版本号" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="应用状态" prop="status">-->
<!--          <el-select v-model="form.status" placeholder="请选择应用状态">-->
<!--            <el-option-->
<!--              v-for="dict in dict.type.app_status"-->
<!--              :key="dict.value"-->
<!--              :label="dict.label"-->
<!--              :value="parseInt(dict.value)"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="应用评分" prop="rating">-->
<!--          <el-input v-model="form.rating" placeholder="请输入应用评分" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="下载数量" prop="downloadCount">-->
<!--          <el-input v-model="form.downloadCount" placeholder="请输入下载数量" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="应用ICON" prop="iconUrl">-->
<!--          <image-upload v-model="form.iconUrl"/>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="应用大小" prop="size">-->
<!--          <el-input v-model="form.size" placeholder="请输入应用大小" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="应用下载地址" prop="downloadUrl">-->
<!--          <el-input v-model="form.downloadUrl" placeholder="请输入应用下载地址" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="是否新机必备" prop="essentialForNewDevices">-->
<!--          <el-input v-model="form.essentialForNewDevices" placeholder="请输入是否新机必备" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="上一版本号" prop="oldVersion">-->
<!--          <el-input v-model="form.oldVersion" placeholder="请输入上一版本号" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="上衣版本大小" prop="oldSize">-->
<!--          <el-input v-model="form.oldSize" placeholder="请输入上衣版本大小" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="BUNDLE NAME" prop="bundleName">-->
<!--          <el-input v-model="form.bundleName" placeholder="请输入BUNDLE NAME" />-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--      <div slot="footer" class="dialog-footer">-->
<!--        <el-button type="primary" @click="submitForm">确 定</el-button>-->
<!--        <el-button @click="cancel">取 消</el-button>-->
<!--      </div>-->
<!--    </el-dialog>-->

      <template>
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
          <el-form ref="uploadForm" :model="uploadForm" :rules="uploadRules" label-width="80px">
            <el-form-item label="应用名称" prop="name">
              <el-input v-model="uploadForm.name" placeholder="请输入应用名称" @input="checkFormCompletion"/>
            </el-form-item>

            <el-form-item label="应用简介" prop="description">
              <el-input v-model="uploadForm.description" placeholder="请输入应用简介" @input="checkFormCompletion"/>
            </el-form-item>

            <el-form-item label="类别" prop="category">
              <el-select v-model="uploadForm.category" placeholder="请选择类别" @change="checkFormCompletion">
                <el-option value="0" label="类别1"></el-option>
                <el-option value="1" label="类别2"></el-option>
                <el-option value="2" label="类别3"></el-option>
                <el-option value="3" label="类别4"></el-option>
                <el-option value="4" label="类别5"></el-option>
                <el-option value="5" label="类别6"></el-option>
              </el-select>
            </el-form-item>

<!--            <el-form-item label="开发者ID" prop="developerId">-->
<!--              <el-input v-model="uploadForm.developerId" placeholder="请输入开发者ID" @input="checkFormCompletion"/>-->
<!--            </el-form-item>-->

<!--            <el-form-item label="应用大小" prop="size">-->
<!--              <el-input v-model="uploadForm.size" placeholder="请输入应用大小" @input="checkFormCompletion" readonly/>-->
<!--            </el-form-item>-->

            <el-form-item label="JSON配置文件" prop="moduleJson">
              <input type="file" @change="handleFileChange('moduleJson', $event)" />
            </el-form-item>

            <el-form-item label="应用包" prop="fileInput">
              <input type="file" @change="handleFileChange('file', $event)" />
            </el-form-item>

            <el-form-item label="应用图标" prop="avatar">
              <input type="file" @change="handleFileChange('avatar', $event)" />
            </el-form-item>

            <el-form-item label="详细图像" prop="detailImages">
              <input type="file" @change="handleDetailImagesChange" multiple />
            </el-form-item>
          </el-form>

          <p v-if="uploadStatus">{{ uploadStatus }}</p>

          <div slot="footer" class="dialog-footer">
  <!--          <el-button type="primary" :disabled="isDisabled" @click="handleAppUpload">上传应用</el-button>-->
            <el-button type="primary" v-if="title === '添加应用详情'" @click="handleSubmit">上传应用</el-button>
            <el-button type="primary" v-if="title === '修改应用详情'" @click="handleUpdateSubmit">更新应用</el-button>
            <el-button @click="cancel">取消</el-button>
          </div>
        </el-dialog>
      </template>

  </div>
</template>

<script>
import { listApp, getApp, delApp, addApp, updateApp } from "@/api/appstoredev/app";
import { getToken } from "@/utils/auth";
import axios from 'axios';
import store from "@/store";
import modal from "../../../plugins/modal";

export default {
  name: "App",
  dicts: ['app_status', 'app_catgory'],
  data() {
    return {
      currentId: 0,
      userId: store.state.id,
      files: {
        file: null,
        avatar: null,
        avatar1: null, // 确保这里有 avatar1
        detailImages: [],
        moduleJson: null
      },
      // 上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        // url: process.env.VUE_APP_BASE_API + "/common/upload",
        // url: "http://192.168.0.131:8889/app/upload",
        url: process.env.VUE_APP_BASE_API + "/app/upload",
        // 上传的hap列表
        hapFileList: [],
        // 上传的icon
        iconFileList: [],
        // 上传的详情图片列表
        detailFileList: []
      },
      uploadStatus: '',
      isDisabled: false,
      selectedFiles: {
        file: null,
        avatar: null,
        detailImages: [],
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 应用详情表格数据
      appList: [],
      // 弹出层标题
      title: "应用上传",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        categoryId: null,
        status: null,

      },
      // 表单参数
      form: {

      },
      // 上传表单
      uploadForm: {
        name: '',
        description: '',
        category: '',
        developerId: '1',
        size: '',
        hapFileList: [],
        iconFileList: [],
        detailFileList: []
      },
      //上传表单校验
      uploadRules: {
        name: [{ required: true, message: '请输入应用名称', trigger: 'blur' }],
        description: [{ required: true, message: '请输入应用简介', trigger: 'blur' }],
        category: [{ required: true, message: '请选择应用类别', trigger: 'change' }],
        developerId: [{ required: true, message: '请输入开发者ID', trigger: 'blur' }],
      },
      // 表单校验
      rules: {
        id: [
          { required: true, message: "应用ID不能为空", trigger: "blur" }
        ],
        downloadUrl: [
          { required: true, message: "应用下载地址不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleFileChange(field, event) {
      const file = event.target.files[0];
      if (file) {
        const fileSize = this.formatFileSize(file.size);
        console.log("fileSize is ", fileSize)
        this.uploadForm.size = fileSize;
      }
      this.files[field] = event.target.files[0];  // 处理单个文件
    },
    handleDetailImagesChange(event) {
      // this.files.detailImages = event.target.files;  // 处理多个文件
      this.files.detailImages = Array.from(event.target.files);
    },

    /** 查询应用详情列表 */
    getList() {
      this.loading = true;
      listApp(this.queryParams).then(response => {
        this.appList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        description: null,
        categoryId: null,
        developerId: null,
        version: null,
        status: null,
        rating: null,
        downloadCount: null,
        iconUrl: null,
        size: null,
        downloadUrl: null,
        essentialForNewDevices: null,
        oldVersion: null,
        oldSize: null,
        bundleName: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加应用详情";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      this.currentId = id
      getApp(id).then(response => {
        this.uploadForm = response.data;
        this.open = true;
        this.title = "修改应用详情";
      });
    },

    handleSubmit() {
      const formData = new FormData();

      // 添加json文件信息
      formData.append("app", JSON.stringify({
        name: this.uploadForm.name,
        description: this.uploadForm.description,
        categoryId: this.uploadForm.category,
        developerId: "1",
        size: this.uploadForm.size,
      }));
      // 添加文件和文本信息到 FormData
      formData.append('file', this.files.file);
      formData.append('avatar', this.files.avatar);
      if (Array.isArray(this.files.detailImages)) {
        this.files.detailImages.forEach(file => formData.append('detailImages', file));
      } else {
        console.error('detailImages is not an array', this.files.detailImages);
      }
      // this.files.detailImages.forEach(file => formData.append('detailImages', file));
      formData.append('moduleJson', this.files.moduleJson);
      // formData.append('app', this.appString);
      // formData.append('app', "asdasd");
      console.log("userid 为", this.$store.state.id)

      // 检查 FormData 的内容
      for (const [key, value] of formData.entries()) {
        if (value instanceof File) {
          console.log(`${key}: ${value.name}`);
        } else {
          console.log(`${key}: ${value}`);
        }
      }

      // 获取用户的 token
      const token = getToken();
      console.log("token is ", token)

      // 设置上传的请求头部
      const config = {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'multipart/form-data'
        },
      };

      // 使用 axios 发送请求
      axios.post('http://192.168.0.132:8080/app/upload', formData, config)
        .then(response => {
          console.log('Upload successful', response);
          console.log("response.msg is ", response.data.msg)
          modal.alert(response.data.msg)
        })
        .catch(error => {
          console.error('Upload failed', error);
          modal.alert(error)
        });
    },

    // 更新应用方法
    handleUpdateSubmit() {
      const formData = new FormData();

      // 添加json文件信息
      formData.append("app", JSON.stringify({
        name: this.uploadForm.name,
        description: this.uploadForm.description,
        categoryId: this.uploadForm.category,
        developerId: "1",
        size: this.uploadForm.size
      }));

      // 添加文件和文本信息到 FormData
      formData.append('file', this.files.file);
      formData.append('avatar', this.files.avatar);
      if (Array.isArray(this.files.detailImages)) {
        this.files.detailImages.forEach(file => formData.append('detailImages', file));
      } else {
        console.error('detailImages is not an array', this.files.detailImages);
      }
      // this.files.detailImages.forEach(file => formData.append('detailImages', file));
      formData.append('moduleJson', this.files.moduleJson);
      // formData.append('app', this.appString);
      // formData.append('app', "asdasd");
      console.log("userid 为", this.$store.state.id)
      formData.append("appId", this.currentId)
      console.log("更新操作的传参内容")
      // 检查 FormData 的内容
      for (const [key, value] of formData.entries()) {
        if (value instanceof File) {
          console.log(`${key}: ${value.name}`);
        } else {
          console.log(`${key}: ${value}`);
        }
      }

      // 获取用户的 token
      const token = getToken();
      console.log("token is ", token)

      // 设置上传的请求头部
      const config = {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'multipart/form-data'
        },
      };

      // 使用 axios 发送请求
      axios.post('http://192.168.0.132:8080/app/update', formData, config)
        .then(response => {
          console.log('Upload successful', response);
          console.log("response.msg is ", response.data.msg)
          modal.alert(response.data.msg)
        })
        .catch(error => {
          console.error('Upload failed', error);
          modal.alert(error)
        });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateApp(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addApp(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除应用详情编号为"' + ids + '"的数据项？').then(function() {
        return delApp(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('appstoredev/app/export', {
        ...this.queryParams
      }, `app_${new Date().getTime()}.xlsx`)
    },
    // handleFileChange(type, fileList) {
    //   console.log("开始操作handleFileChange")
    //   console.log("type is ", type)
    //   console.log("fileList is ", fileList)
    //   if (type === 'file') {
    //     this.uploadForm.hapFileList = fileList;
    //     this.selectedFiles.file = fileList[0];
    //   } else if (type === 'avatar') {
    //     this.uploadForm.iconFileList = fileList;
    //     this.selectedFiles.avatar = fileList[0];
    //   } else if (type === 'detailImages') {
    //     this.uploadForm.detailFileList = fileList;
    //     this.selectedFiles.detailImages = fileList;
    //   }
    //   this.checkFormCompletion();
    //   // this.validateInputs();
    // },
    // 在每次表单内容变化时检查提交按钮状态
    checkFormCompletion() {
      console.log("form表单为", this.uploadForm)
      const { name, description, category, developerId, size } = this.uploadForm;
      const isFileUploaded = this.uploadForm.hapFileList.length > 0 && this.uploadForm.avatar.length > 0 && this.uploadForm.detailImages.length > 0;
      console.log("isFileUpLoaded is ", isFileUploaded)
      // 当所有字段都填写并且文件上传完成时启用提交按钮
      this.isDisabled = !(name && description && category && developerId && size && isFileUploaded);
    },

    formatFileSize(size) {
      if (size < 1024) return `${size} B`;
      else if (size < 1024 * 1024) return `${(size / 1024).toFixed(2)} KB`;
      else if (size < 1024 * 1024 * 1024) return `${(size / 1024 / 1024).toFixed(2)} MB`;
      else return `${(size / 1024 / 1024 / 1024).toFixed(2)} GB`;
    },
    beforeFileUpload(file) {
      // You can add file validation here, e.g., check file size, type
      return true;
    },
    validateInputs() {
      const { name, description, category, developerId, size } = this.uploadForm;
      this.isDisabled = !(name && description && category && developerId && size && this.selectedFiles.file && this.selectedFiles.avatar);
    },

    handleAppUpload() {
      const formData = new FormData();
      formData.append("file", this.selectedFiles.file);
      formData.append("avatar", this.selectedFiles.avatar);
      this.selectedFiles.detailImages.forEach((file) => {
        formData.append("detailImages", file);
      });
      console.log(JSON.stringify(this.uploadForm))
      formData.append("app", JSON.stringify(this.uploadForm));

      this.uploadStatus = '上传中...';

      fetch(this.upload.url, {
        method: 'POST',
        body: formData
      })
        .then((response) => response.json())
        .then((data) => {
          if (data.code === 200) {
            this.uploadStatus = '上传成功！';
            modal.alert(data.msg)
          } else {
            this.uploadStatus = `上传失败: ${data.msg}`;
            modal.alert(data.msg)
          }
        })
        .catch((error) => {
          this.uploadStatus = '上传失败，请稍后再试。';
          console.error("上传错误:", error);
          modal.alert(error)
        });
    },

    // 文件提交处理
    submitUpload() {
      this.$refs.upload.submit();
    },
// 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
// 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      console.log("文件上传成功, url 为", JSON.stringify(response))
      console.log("文件上传成功, file 为", file)
      console.log("文件上传成功, fileList 为", fileList)
      this.upload.isUploading = false;
      this.upload.filePath = response.url;
      this.msgSuccess(response.msg);
    },
  }
};
</script>
